#coding=utf-8

import hashlib
import web
import os
import time
import settings

##http://my.oschina.net/yangyanxing/blog/159215

app_root = os.path.dirname(__file__)
templates_root = os.path.join(app_root,'templates')
render = web.template.render(templates_root)

class Weixin:
    ##http://localhost:8080/weixin?signature=1&timestamp=11&nonce=add&echostr=1234
    def GET(self):
        data = web.input()
        signature = data.signature
        timestamp = data.timestamp
        nonce = data.nonce
        echostr = data.echostr

        token = "yourtoken"
        list = [token,timestamp,nonce]
        list.sort()
        sha1 = hashlib.sha1()
        map(sha1.update,list)
        hashcode = sha1.hexdigest()

        if hashcode == signature:
            return echostr
        else:
            return "failed: " + signature + " please use the same token" + "\r\n" + templates_root

    @property
    def POST(self):
        str_xml = web.data()
        from xml.etree import ElementTree as ET
        root = ET.fromstring(str(str_xml))

        fromUser = root.findtext(".//FromUserName")
        toUser = root.findtext(".//ToUserName")
        createTime = root.findtext(".//CreateTime")
        msgType = root.findtext(".//MsgType")
        msgId = root.findtext(".//MsgId")

        if msgType == 'text':
            content = str(root.findtext(".//Content"))
            if content.find(u'翻译') > -1:
                content = content.replace(u"翻译","")
            congdongurl = 'http://www.tuling123.com/openapi/api?key=0c102b2a37e1aba4a1467475fe40d086&info=' + content
            return render.reply_text(fromUser,toUser,createTime, "text " + content)
        elif msgType == 'image':
            return render.reply_text(fromUser,toUser,createTime, "image ")
        elif msgType == 'voice':
            return render.reply_text(fromUser,toUser,createTime, "image ")
        elif msgType == 'video':
            return render.reply_text(fromUser,toUser,createTime, "image ")
        elif msgType == 'location':
            return render.reply_text(fromUser,toUser,createTime, "image ")
        elif msgType == 'link':
            return render.reply_text(fromUser,toUser,createTime, "image ")
        else:
            return render.reply_text(fromUser,toUser,createTime, "other ")

def youdao():
    import urllib2
    word = urllib2.quote('杭州')
    print word

if __name__ == '__main__':
    youdao()